package com.hjq.mallmember.interceptor;

import com.hjq.common.constants.AuthConstants;
import com.hjq.common.entity.vo.UserAccountVO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther HJQ
 */
@Component
public class MemberLoginInterceptor implements HandlerInterceptor {
    public  static  ThreadLocal<UserAccountVO> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //排除请求
        String requestURI = request.getRequestURI();
        ArrayList<Boolean> match = new ArrayList<>();
        match.add(new AntPathMatcher().match("/mallmember/member/**", requestURI));
        match.add(new AntPathMatcher().match("/mallmember/memberreceiveaddress/**", requestURI));
        if(matchOne(match)){
            return true;

        }

        //其他请求要有session
        HttpSession session = request.getSession();
        UserAccountVO attribute =(UserAccountVO) session.getAttribute(AuthConstants.LOGIN_USER);
        if(attribute!=null){
            threadLocal.set(attribute);
            return true;
        }
        else {
            response.sendRedirect("http://auth.hjqmall.com/login.html");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    private boolean matchOne(List<Boolean> matches){
        boolean match=false;
        for (Boolean b : matches) {
            match=b||match;
        }
        return match;

    }
}
